import React, { memo, useMemo } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

interface OptimizedChartProps {
  data: any[];
  height?: number;
}

export const OptimizedChart: React.FC<OptimizedChartProps> = memo(({ data, height = 300 }) => {
  // 只渲染最新50条数据以提升性能
  const chartData = useMemo(() => {
    return data.slice(-50).map(item => ({
      ...item,
      pressure: item.pressure ? item.pressure / 10 : undefined // 缩放气压数据
    }));
  }, [data]);

  // 动态生成线条配置
  const lineConfigs = useMemo(() => {
    if (chartData.length === 0) return [];
    
    const colors = ['#8884d8', '#82ca9d', '#ffc658', '#ff7300', '#8dd1e1'];
    const metricNames: Record<string, string> = {
      temperature: '温度(°C)',
      humidity: '湿度(%)',
      windSpeed: '风速(m/s)',
      visibility: '能见度(km)',
      uvIndex: 'UV指数',
      pressure: '气压(×10 hPa)'
    };

    return Object.keys(chartData[0] || {})
      .filter(key => typeof chartData[0]?.[key] === 'number' && !['time'].includes(key))
      .map((key, index) => ({
        key,
        name: metricNames[key] || key,
        color: colors[index % colors.length]
      }));
  }, [chartData]);

  if (chartData.length === 0) {
    return (
      <div style={{ 
        height, 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        color: '#999'
      }}>
        暂无图表数据
      </div>
    );
  }

  return (
    <ResponsiveContainer width="100%" height={height}>
      <LineChart data={chartData}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis 
          dataKey="time" 
          tick={{ fontSize: 12 }}
          interval="preserveStartEnd"
        />
        <YAxis tick={{ fontSize: 12 }} />
        <Tooltip 
          contentStyle={{ fontSize: 12 }}
          labelStyle={{ fontSize: 12 }}
        />
        <Legend wrapperStyle={{ fontSize: 12 }} />
        {lineConfigs.map(config => (
          <Line
            key={config.key}
            type="monotone"
            dataKey={config.key}
            stroke={config.color}
            name={config.name}
            strokeWidth={2}
            dot={{ r: 3 }}
            activeDot={{ r: 4 }}
          />
        ))}
      </LineChart>
    </ResponsiveContainer>
  );
});

OptimizedChart.displayName = 'OptimizedChart';

export default OptimizedChart;